/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller.b;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.dto.CnActivityDTO;
import com.ykht.proj.activity.dto.CnActivityShopVO;
import com.ykht.proj.activity.entity.CnActivity;
import com.ykht.proj.activity.service.CnActivityService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.api.feign.RemoteShopService;
import com.ykht.proj.coupon.entity.CnShop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 活动表
 *
 * @author csg
 * @date 2020-12-23 11:13:32
 */
@RestController
@AllArgsConstructor
@RequestMapping("/b/cnactivity/")
@Api(value = "cnactivity", tags = "活动表管理")
@Slf4j
public class BnActivityController {

	private final CnActivityService cnActivityService;
	private final RemoteShopService remoteShopService;

	/**
	 * 活动验证参数（添加和修改）
	 *
	 * @return R
	 */
	@ApiOperation(value = "活动验证参数（添加和修改）")
	@SysLog("活动验证参数（添加和修改）")
	@PostMapping("checkParameter")
	public R checkParameter(@RequestBody CnActivityDTO cnActivityDTO) {
		try {
			QueryWrapper<CnActivity> queryWrapper = new QueryWrapper<>();
			CnActivity activity = null;
			if (null != cnActivityDTO.getName()) { // 活动名称
				queryWrapper.lambda().eq(CnActivity::getName, cnActivityDTO.getName());
				activity = cnActivityService.getOne(queryWrapper);
				if (null != activity && !activity.getId().equals(cnActivityDTO.getId())) {
					return R.ok(false);
				}
			} else if (null != cnActivityDTO.getExternalTitle()) { // 活动外显标题
				queryWrapper.lambda().eq(CnActivity::getExternalTitle, cnActivityDTO.getExternalTitle());
				activity = cnActivityService.getOne(queryWrapper);
				if (null != activity && !activity.getId().equals(cnActivityDTO.getId())) {
					return R.ok(false);
				}
			} else if (null != cnActivityDTO.getVipTitle()) { // 会员卡标题（卡名）
				queryWrapper.lambda().eq(CnActivity::getVipTitle, cnActivityDTO.getVipTitle());
				activity = cnActivityService.getOne(queryWrapper);
				if (null != activity && !activity.getId().equals(cnActivityDTO.getId())) {
					return R.ok(false);
				}
			} else if (null != cnActivityDTO.getSort()) { // 排序数字
				queryWrapper.lambda().eq(CnActivity::getSort, cnActivityDTO.getSort());
				activity = cnActivityService.getOne(queryWrapper);
				if (null != activity && !activity.getId().equals(cnActivityDTO.getId())) {
					return R.ok(false);
				}
			} else if (null != cnActivityDTO.getTypeName()) { // 分类名称
				queryWrapper.lambda().eq(CnActivity::getTypeName, cnActivityDTO.getTypeName());
				activity = cnActivityService.getOne(queryWrapper);
				if (null != activity && !activity.getId().equals(cnActivityDTO.getId())) {
					return R.ok(false);
				}
			}
			return R.ok(true);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 新增活动表
	 *
	 * @return R
	 */
	@ApiOperation(value = "新增活动表")
	@SysLog("新增活动表")
	@PostMapping("addCnActivity")
	public R addCnActivity(@RequestBody CnActivityDTO cnActivityDTO) {
		try {
			log.info("->新增活动表:{}", JSONUtil.toJsonStr(cnActivityDTO));
			Assert.isTrue(null != cnActivityDTO.getShopIds()
					&& cnActivityDTO.getShopIds().length > 0, "选择门店（商铺）不能为空");
			cnActivityDTO.setCreateUser(SecurityUtils.getUserId());
			cnActivityDTO.setCreateTime(LocalDateTime.now());
			cnActivityDTO.setDelFlag(0);
			cnActivityService.addCnActivity(cnActivityDTO);
			return R.ok("创建成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 修改活动表（上下架）
	 *
	 * @return R
	 */
	@ApiOperation(value = "修改活动表（上下架）")
	@SysLog("修改活动表（上下架）")
	@GetMapping("updateCnActivity")
	public R updateCnActivity(CnActivity cnActivity) {
		try {
			log.info("->修改活动表（上下架）:{}", JSONUtil.toJsonStr(cnActivity));
			Assert.isTrue(null != cnActivity.getId(), "id不能为空");
			cnActivity.setUpdateUser(SecurityUtils.getUserId());
			cnActivity.setUpdateTime(LocalDateTime.now());
			cnActivityService.updateById(cnActivity);
			return R.ok("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 修改活动表(并同时修改 商铺活动关联表)
	 *
	 * @return R
	 */
	@ApiOperation(value = "修改活动表(并同时修改 商铺活动关联表)")
	@SysLog("修改活动表(并同时修改 商铺活动关联表)")
	@PostMapping("updateCnActivityAndShopIds")
	public R updateCnActivityAndShopIds(@RequestBody CnActivityDTO cnActivityDTO) {
		try {
			log.info("->修改活动表(并同时修改 商铺活动关联表):{}", JSONUtil.toJsonStr(cnActivityDTO));
			Assert.isTrue(null != cnActivityDTO.getShopIds()
					&& cnActivityDTO.getShopIds().length > 0, "选择门店（商铺）不能为空");
			Assert.isTrue(null != cnActivityDTO.getId(), "id不能为空");
			cnActivityDTO.setUpdateUser(SecurityUtils.getUserId());
			cnActivityDTO.setUpdateTime(LocalDateTime.now());
			cnActivityService.updateCnActivityAndShopIds(cnActivityDTO);
			return R.ok("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 活动展示（分页，搜索）
	 *
	 * @param page
	 * @param cnActivityDTO
	 * @return
	 */
	@ApiOperation(value = "活动展示（分页，搜索）")
	@SysLog("活动展示（分页，搜索）")
	@GetMapping("getCnActivityListPage")
	public R getCnActivityListPage(Page page, CnActivityDTO cnActivityDTO) {
		try {
			log.info("->活动展示（分页，搜索）", JSONUtil.toJsonStr(cnActivityDTO));
			QueryWrapper<CnActivity> queryWrapper = new QueryWrapper<>();
			if (null != cnActivityDTO.getName()) {
				queryWrapper.lambda().like(CnActivity::getName, cnActivityDTO.getName());
			}
			if (null != cnActivityDTO.getCreateTimeStart()) {
				queryWrapper.lambda().ge(CnActivity::getCreateTime, cnActivityDTO.getCreateTimeStart());
			}
			if (null != cnActivityDTO.getCreateTimeEnd()) {
				queryWrapper.lambda().le(CnActivity::getCreateTime, cnActivityDTO.getCreateTimeEnd());
			}
			return R.ok(cnActivityService.page(page, queryWrapper));
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}


	/**
	 * 根据ID 获取活动详情
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "根据ID 获取活动详情")
	@SysLog("根据ID 获取活动详情")
	@GetMapping("getByIdCnActivity")
	public R getByIdCnActivity(Long id) {
		try {
			log.info("->根据ID 获取活动详情", id);
			CnActivityDTO byIdCnActivity = cnActivityService.getByIdCnActivity(id);
			if (null != byIdCnActivity.getShopIdShow()) {
				List<CnActivityShopVO> cnActivityShopVOList = new ArrayList<>();
				List<CnShop> cnShopList = remoteShopService.getByIds(byIdCnActivity.getShopIdShow().split(","));
				cnShopList.stream().forEach(itme -> {
					CnActivityShopVO bean = BeanUtil.toBean(itme, CnActivityShopVO.class);
					cnActivityShopVOList.add(bean);
				});
				byIdCnActivity.setCnActivityShopVOList(cnActivityShopVOList);
			}
			return R.ok(byIdCnActivity);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

}
